import { memo, useEffect, useState } from 'react';
import { Position, useReactFlow, Node } from '@xyflow/react';
import { Card, Form, Input, Modal, Select, Space, Spin } from 'antd';
import Subtitle from '../../components/Subtitle';
import useSelectBorder from '../../store/useSceneData';
import CustomHandle from '../CustomHandle';
import { Loading3QuartersOutlined } from '@ant-design/icons';
import NodeOperation from '../../components/NodeOperation';
import LlmSelect from '../../components/LlmSelect';

/**
 * 流程节点
 * @param param0 
 * @returns 
 */

function IfNode({ id, data }: Node) {
  const { setNodes, setCenter } = useReactFlow();
  const { select, setSelectId, debug, setDeBug } = useSelectBorder()
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [variable, setVariable] = useState<string>();

  const handleFocus = () => {
    setSelectId(id);
    setDeBug(false)
  };

  useEffect(() => {
    if (data.param) {
      const result = data.result || ""
      setVariable(data.param + " " + data.equal + " " + result)
    }
  }, [])

  useEffect(() => {
    if (select[id] && debug) {
      setNodes((nodes) => {
        const node = nodes.find(node => node.id == id)
        setCenter(node.position.x + 200, node.position.y, { zoom: 1, duration: 500 })
        return [...nodes];
      })
    }
  }, [select[id]])

  return (
    <NodeOperation nodeId={id} onClick={() => {
      form.setFieldsValue(data)
      setIsModalOpen(true)
    }}>
      <Card
        title={<div className='flex'>
          <Subtitle imgUrl='img/if.png' title={data.title as string || '条件分支'} id={id} />
          {select[id] && debug && <Spin indicator={<Loading3QuartersOutlined spin />} className='mt-[6px] ml-2' />}
        </div>}
        style={{
          outline: select[id] ? "2px solid #145FF0" : "none",
          position: 'relative',
          width: 310,
          height: 160,
        }}
        onClick={handleFocus}
        tabIndex={0}
      >
        <CustomHandle count={2} type="target" position={Position.Left} id="llmStart" style={{ top: 74 }} />
        <Modal
          title={<span>{data.title as string || '条件分支'}</span>}
          open={isModalOpen}
          destroyOnClose={true}
          width={500}
          onOk={() => {
            setVariable(form.getFieldValue('param') + " " + form.getFieldValue('equal') + " " + form.getFieldValue('result'))
            setIsModalOpen(false);
            setNodes((nodes) => {
              const node = nodes.find(node => node.id == id)
              node.data.param = form.getFieldValue('param')
              node.data.equal = form.getFieldValue('equal')
              node.data.result = form.getFieldValue('result')
              return [...nodes];
            })
          }}
          onCancel={() => setIsModalOpen(false)}>
          <div className='flex flex-col'>
            <div className='font-bold text-[#485468] mt-2'>IF</div>
            <Form className='flex mt-2' form={form}>
              <Space>
                <Form.Item name="param" >
                  <LlmSelect />
                </Form.Item>
                <Form.Item className='w-[100px]' name="equal">
                  <Select
                    options={[
                      { label: '等于', value: 'equal' },
                      { label: '包含', value: 'Include' },
                      { label: '空', value: 'null' },
                      { label: '非空', value: 'nodeNull' },
                    ]} />
                </Form.Item>
                <Form.Item
                  noStyle
                  dependencies={['equal']}
                >
                  {({ getFieldValue }) => {
                    const equal = getFieldValue('equal');
                    return <Form.Item name="result">
                      <Input disabled={equal == "null" || equal == "nodeNull"} autoComplete='off' />
                    </Form.Item>
                  }}
                </Form.Item>
              </Space>
            </Form>
          </div>
        </Modal>
        <div className='flex'>
          {variable && <div className='bg-[#F3F4F7] w-full mt-3 p-1 rounded-lg pl-2 text-[#667085]'>
            {variable}
          </div>}
          <div className='pl-10 h-[32px] absolute' style={{ fontWeight: 'bold' }}>
            <div className='text-[#485468]' style={{ position: 'absolute', left: 250, top: -16 }}>IF</div>
            <div className='text-[#485468]' style={{ position: 'absolute', left: 230, top: 50 }}>ELSE</div>
          </div>
        </div>
        <CustomHandle count={1} type="source" position={Position.Right} id="llmIf" style={{ top: 74 }} />
        <CustomHandle count={1} type="source" position={Position.Right} id="llmElse" style={{ top: 140 }} />
      </Card>
    </NodeOperation >
  );
}

export default memo(IfNode)